package com.lingyun.financialmanagement.service.pojo;

import com.lingyun.financialmanagement.dao.mapper.UsersMapper;
import com.lingyun.financialmanagement.dao.pojo.Users;
import com.lingyun.financialmanagement.service.LoginService;
import com.lingyun.financialmanagement.utils.JWTUtils;
import com.lingyun.financialmanagement.vo.ErrorCode;
import com.lingyun.financialmanagement.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${redis.token.tokenAccountPrefix}")
    private String tokenAccountPrefix;

    @Value("${redis.token.tokenRolePrefix}")
    private String tokenRolePrefix;

    @Value("${redis.token.TokenToRedisDate}")
    private Integer TokenToRedisDate;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Boolean checkToken(String token) {
        if (token == null || token.isEmpty()){
            log.info("token不能为空");
            return false;
        }
        String account = null;
        try{
            account = redisTemplate.opsForValue().get(tokenAccountPrefix + token);
        } catch (Exception e){
            log.error("验证时：redis错误！");
            return false;
        }
        if (account == null || account.isEmpty()) {
            log.info("未在redis中找到此token");
            return false;
        }
        return true;
    }

    @Override
    public Result login(String account, String password, Boolean remember) {
        Users users = usersMapper.selectByAccount(account);
        if (users == null){
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        // 获取数据库md5数据
        String sqlPassword = users.getPassword();
        // 获取登录账号md5数据
        String password2 = DigestUtils.md5DigestAsHex(password.getBytes());

        // 密码错误
        if (!sqlPassword.equals(password2)) {
            return Result.fail(ErrorCode.PASSWORD_ERROR.getCode(), ErrorCode.PASSWORD_ERROR.getMsg());
        }

        // 获取token
        String token = JWTUtils.createToken(account);

        if (remember){
            // 设置redis
            try{
                redisTemplate.opsForValue().set(tokenAccountPrefix + token, account, TokenToRedisDate, TimeUnit.DAYS);
                redisTemplate.opsForValue().set(tokenRolePrefix + account, users.getRole(), TokenToRedisDate, TimeUnit.DAYS);
            } catch (Exception e) {
                return Result.fail(ErrorCode.REDIS_ERROR.getCode(), ErrorCode.REDIS_ERROR.getMsg());
            }
        }else {
            try{
                redisTemplate.opsForValue().set(tokenAccountPrefix + token, account, 30, TimeUnit.MINUTES);
                redisTemplate.opsForValue().set(tokenRolePrefix + account, users.getRole(), 30, TimeUnit.MINUTES);
            } catch (Exception e) {
                return Result.fail(ErrorCode.REDIS_ERROR.getCode(), ErrorCode.REDIS_ERROR.getMsg());
            }
        }


        // 如果多做一个步骤
        // 登录后查找redis值是否有account，然后删掉创建新的值（也就成为了一个手机只能登录一个用户）
        ArrayList<String> result = new ArrayList<>();
        result.add(token);
        result.add(users.getRole());
        return Result.success(result);
    }

    @Override
    public Result logout() {
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()){
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        String account = redisTemplate.opsForValue().get(tokenAccountPrefix + token);
        // 如果获取的账号为空
        if (account == null || account.isEmpty()) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        redisTemplate.delete(tokenAccountPrefix + token);

        return null;
    }
}
